﻿using System;
using System.Windows;
using Microsoft.Phone.Controls;
using RestServicesSample.Model;
using RestServicesSample.Services;
using System.Collections.ObjectModel;

namespace RestServicesSample
{
    public partial class MainPage : PhoneApplicationPage
    {
        private SampleApi service = new SampleApi();
        public ObservableCollection<User> MyContacts = new ObservableCollection<User>();
        
        public MainPage()
        {
            InitializeComponent();
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            service.GetUsers(
                success =>
                {
                    MyContacts.Clear();
                    foreach (User u in success.user)
                    {
                        MyContacts.Add(u);
                    }

                    ContactList.DataContext = MyContacts;
                },
                fail =>
                {
                    MessageBox.Show("Something goes wrong");
                });
        }

        private void listUser(object sender, RoutedEventArgs e)
        {
           NavigationService.Navigate(new Uri("/ListUser.xaml", UriKind.Relative));
        }

        private void AddButtonClicked(object sender, EventArgs e)
        {
            NavigationService.Navigate(new
                Uri(String.Format("/FormUser.xaml?action={0}", Global.InsertAction), UriKind.Relative));
        }

        private void ContactListSelected(object sender, System.Windows.Input.GestureEventArgs e)
        {
            Global.Instance.User = (User) ContactList.SelectedItem;
            NavigationService.Navigate(new 
                Uri(String.Format ("/FormUser.xaml?action={0}", Global.UpdateAction), UriKind.Relative));
        }
    }
}